package engine

import (
	"net/http"

	"gitcode.com/eteam/sae.git/types"
	"github.com/gin-gonic/gin"
)

func (sae *SimpleAgentEngine) listSkill(ctx *gin.Context) {
	userInfo, err := sae.cfg.AuthProvider.GetUserInfo(ctx.Request)
	if err != nil {
		ctx.String(403, err.Error())
		return
	}
	skillInfoList := sae.doListSkill(ctx.Request, userInfo.UserRole)
	ctx.JSON(200, skillInfoList)
}

func (sae *SimpleAgentEngine) doListSkill(req *http.Request, userRole string) []*types.Skill {

	skillInfoList := []*types.Skill{}
	for _, skillProvider := range sae.cfg.SkillProviderList {
		skillInfo := skillProvider.GetInfo()
		if skillInfo.FilterUserRole {
			match := false
			for _, cmpRole := range skillInfo.UserRoles {
				if cmpRole == userRole {
					match = true
				}
			}
			if match {
				skillInfoList = append(skillInfoList, skillInfo)
			}
		} else {
			skillInfoList = append(skillInfoList, skillInfo)
		}
	}
	return skillInfoList
}

func (sae *SimpleAgentEngine) guessSkill(ctx *gin.Context) {
	userInfo, err := sae.cfg.AuthProvider.GetUserInfo(ctx.Request)
	if err != nil {
		ctx.String(403, err.Error())
		return
	}
	skillInfoList := sae.doListSkill(ctx.Request, userInfo.UserRole)
	var msg types.Message
	err = ctx.BindJSON(&msg)
	if err != nil {
		return
	}
	skillId, err := sae.cfg.GuessSkillFunc(skillInfoList, &msg)
	if err != nil {
		ctx.String(500, err.Error())
		return
	}
	ctx.JSON(200, &GuessSkillResponse{
		SkillId: skillId,
	})
}
